package com.windward.vii.web.controller;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.windward.vii.common.Constants;
import com.windward.vii.common.JsonResult;
import com.windward.vii.common.ResultCode;
import com.windward.vii.dao.entity.Order;
import com.windward.vii.service.GoodsService;
import com.windward.vii.service.OrderService;
import com.windward.vii.service.UserTokenService;
import com.windward.vii.service.weixin.WeixinPayService;
import com.windward.vii.service.weixin.bean.CallbackResponse;
import com.windward.vii.service.weixin.bean.OrderResponse;
import com.windward.vii.utils.StringUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/v1/")
public class WeixinPayController {

    private static Logger logger = LoggerFactory.getLogger(WeixinPayController.class);

    @Resource
    UserTokenService userTokenService;
    @Resource
    GoodsService goodsService;
    @Resource
    OrderService orderService;
    @Resource
    WeixinPayService weixinPayService;

    /**
     * 查询订单支付状态
     * @param sn
     * @return
     */
    @RequestMapping(value = "api0/weixin/pay/query")
    @ResponseBody
    public JsonResult weixinPayQuery(String sn){
        JsonResult jsonResult = JsonResult.error();
        try {
            if (StringUtils.isBlank(sn)) {
                return JsonResult.error("订单号为空");
            }
            Order order = orderService.selectBySn(sn);
            Map map = new HashMap();
            map.put("sn", sn);
            if (order != null) {
                jsonResult = JsonResult.success();
                map.put("status", order.getStatus());
                if (order.getStatus() == Constants.Order.DELIVER_STATUS_SUCCESS) {
                    map.put("statusDesc", "success");
                    jsonResult.setBody(map);
                } else {
                    jsonResult = weixinPayService.queryOrder(weixinPayService.createOrderRequest(sn));
                    if (jsonResult.getCode() == ResultCode.SUCCESS_CODE) {
                        OrderResponse orderResponse = (OrderResponse) jsonResult.getBody();
                        map.put("statusDesc", orderResponse.getTrade_state_desc());
                        jsonResult.setBody(map);
                    }
                }
            } else {
                logger.error("WeixinPayController.payquery({}),数据库中找不到订单", sn);
                jsonResult.setMsg("找不到订单");
            }
            logger.info("WeixinPayController.payquery({}) response:{}", sn, jsonResult);
            return jsonResult;
        } catch (Exception e) {
            logger.error("WeixinPayController.payquery({}) Exception={}", sn, e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }

    @RequestMapping(value="api0/weixin/pay/callback")
    @ResponseBody
    public String callback(HttpServletRequest req) {
        logger.info("微信支付回调开始...");
        CallbackResponse callbackResponse;
        XmlMapper xmlMapper = new XmlMapper();
        try {
            String content = IOUtils.toString(req.getInputStream());
            logger.info("微信回掉参数" + content);
            if (StringUtils.isNotEmpty(content)) {
                OrderResponse orderResponse = xmlMapper.readValue(content, OrderResponse.class);
                logger.info("读取回调内容，orderResponse={}", orderResponse.toString());
                callbackResponse = validate(orderResponse);
                logger.info("callbackResponse={}", callbackResponse.toString());
                Order order = orderService.selectBySn(orderResponse.getOut_trade_no());
                logger.info("根据订单号获取订单信息，sn={}", orderResponse.getOut_trade_no());
                if (order != null) {
                    logger.info("订单信息不为空，sn={},payOrder={}", orderResponse.getOut_trade_no(), order.toString());
                    if (WeixinPayService.SUCCESS.equals(callbackResponse.getReturn_code())) {
                        if (order.getStatus() != Constants.Order.ORDER_STATUS_DELIVER_SUCCESS) {
                            logger.info("微信支付成功，开始处理账户信息，sn={},payOrder.getStatus={}", order.getSn(), order.getStatus());
                            try {
                                orderService.paySuccess(order, orderResponse.getTransaction_id());
                                logger.info("微信支付成功，处理账户成功,sn={}", order.getSn());
                            } catch (Exception e) {
                                e.printStackTrace();
                                logger.info("微信支付成功，处理账户失败,sn={}", order.getSn());
                                callbackResponse = CallbackResponse.callbackResponseFail("商户订单支付成功" + orderResponse.getOut_trade_no() + "处理失败");
                            }
                        } else {
                            logger.info("该订单已经是支付成功状态，sn={}", order.getSn());
                            callbackResponse = CallbackResponse.callbackResponseSuccess();
                        }
                    } else {
                        logger.info("微信支付失败，开始处理账户数据sn={}", order.getSn());
                        order.setOutTradeNo(orderResponse.getTransaction_id());
                        this.orderService.payFail(order);
                        logger.info("微信支付失败，处理账户数据成功，sn={}", order.getSn());
                    }
                } else {
                    callbackResponse = CallbackResponse.callbackResponseFail("商户订单" + orderResponse.getOut_trade_no() + "不存在");
                }
            } else {
                callbackResponse = CallbackResponse.callbackResponseFail("接收到的参数为空");
            }

            xmlMapper = new XmlMapper();
            String res = xmlMapper.writeValueAsString(callbackResponse);
            logger.info("WeixinPayController.callback({}),response={}", content, res);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("WeixinPayController.callback exception={}", e.getMessage());
            return "<xml><return_code>FAIL</return_code><return_msg>JsonProcessingException</return_msg></xml>";
        }
    }

    private CallbackResponse validate(OrderResponse orderResponse){
        CallbackResponse callbackResponse = CallbackResponse.callbackResponseSuccess();
        if(WeixinPayService.FAIL.equals(orderResponse.getReturn_code())){
            callbackResponse = CallbackResponse.callbackResponseFail(orderResponse.getReturn_msg());
        }else if(WeixinPayService.FAIL.equals(orderResponse.getResult_code())) {
            callbackResponse = CallbackResponse.callbackResponseFail(orderResponse.getErr_code_des());
        }else if(!weixinPayService.verifySign(orderResponse)){
            callbackResponse = CallbackResponse.callbackResponseFail("验证sign失败");
        }
        return callbackResponse;
    }
}
